package com.framework.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.framework.entity.TableEntity;
import com.framework.utils.Tool;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Service;

import com.framework.dao.SysGeneratorDao;
import com.framework.utils.GenUtils;

import static com.framework.utils.GenUtils.tableToJava;

/**
 * 代码生成器
 */
@Service
public class SysGeneratorService {
    @Autowired
    private SysGeneratorDao sysGeneratorDao;

    @Autowired
    private ApplicationArguments applicationArguments;

    public List<Map<String, Object>> queryList(Map<String, Object> map) {
        return sysGeneratorDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return sysGeneratorDao.queryTotal(map);
    }

    public Map<String, String> queryTable(String tableName) {
        return sysGeneratorDao.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return sysGeneratorDao.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for (String tableName : tableNames) {
            // 查询表信息
            Map<String, String> table = queryTable(tableName);
            // 查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);

            // 生成代码
            GenUtils.generatorCode(table, columns, zip);

            String database = applicationArguments.getSourceArgs()[0];
            /**
             * 生成 DOMapper.java  ---   DoMapper.xml
             */
            GenUtils.generator(database,tableName, Tool.underline2Camel(tableName + "DO", true), zip);


        }
        try {
            zip.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }


}
